package reflect.initMethod;

import java.lang.reflect.Constructor;

public class Constructors {
    public static void main(String[] args) throws Exception {
        // 1.加载Class对象
        Class clazz = Class.forName("reflect.initMethod.Student");


        System.out.println("-----获取所有公有构造方法------");
        Constructor[] conArray = clazz.getConstructors();
        for (Constructor c: conArray) {
            System.out.println(c);
        }


        System.out.println("-----获取所有构造方法------");
        conArray = clazz.getDeclaredConstructors();
        for (Constructor c : conArray) {
            System.out.println(c);
        }


        System.out.println("-----获取公有、无参构造方法并调用------");
        Constructor con = clazz.getConstructor(null);
        System.out.println("con=" + con);   // 开始调用
        Object obj = con.newInstance();
        System.out.println("obj=" + obj);
        Student stu = (Student)obj;


        System.out.println("---------获取私有构造方法，并调用----------");
        con = clazz.getDeclaredConstructor(char.class);
        System.out.println("con=" + con);    // 开始调用
        con.setAccessible(true);    // 暴力访问
        obj = con.newInstance('男');

        con = clazz.getDeclaredConstructor(int.class);
        con.setAccessible(true);
        obj = con.newInstance(12);
    }
}
